package com.llkj.qingnianguoxue.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jm.chat.activity.ChatActivity;
import com.jm.chat.application.JGApplication;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.CircleByMeAdapter;
import com.llkj.qingnianguoxue.adapter.MyCircleAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.bean.CircleListBean;
import com.llkj.qingnianguoxue.bean.EventChangeUserBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.ClickViewCallback;
import com.llkj.qingnianguoxue.util.GridSpacingItemDecoration;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Action1;

/**
 * 我的圈子
 */
public class MyCircleFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener, ClickViewCallback {
    private static final int REQUEST_CHAT_CODE = 8935;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView lvActions;
    private MyCircleAdapter myCircleAdapter;
    private List<CircleListBean.CircleBean> mCircleData;
    private int totalSize, mPage,mCurrentPosition;

    private RecyclerView rvCreateByMe;//我创建的
    private CircleByMeAdapter  mCircleByMeAdapter;//我创建的
    private List<CircleListBean.CircleBean> mCircleMeData;//我创建的

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_interest_circle, container, false);
        EventBus.getDefault().register(this);
        initView();
        initListener();

        loadWaitDialog();
        onRefresh();
        return rootView;
    }

    private void initView() {
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvActions = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        lvActions.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        mCircleData = new ArrayList<>();
        myCircleAdapter = new MyCircleAdapter(R.layout.item_my_circle, mCircleData, null);
        myCircleAdapter.setType(2);
        lvActions.setAdapter(myCircleAdapter);

        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.header_my_circle,null);
        rvCreateByMe = (RecyclerView) headerView.findViewById(R.id.rvHeadCircle);
        LinearLayoutManager llLayoutManager = new LinearLayoutManager(getActivity());
        llLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvCreateByMe.setLayoutManager(llLayoutManager);
        myCircleAdapter.addHeaderView(headerView);

        mCircleMeData = new ArrayList<>();
        mCircleByMeAdapter = new CircleByMeAdapter(R.layout.item_circle_by_me,mCircleMeData);
        rvCreateByMe.setAdapter(mCircleByMeAdapter);
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
//        myCircleAdapter.setOnLoadMoreListener(this);
        lvActions.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mCurrentPosition = i;
                CircleListBean.CircleBean circleBean = mCircleData.get(i);

                goChat(circleBean);
            }
        });

        lvActions.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mCurrentPosition = i;
                CircleListBean.CircleBean circleBean = mCircleData.get(mCurrentPosition);
                if(view.getId()== R.id.tvDelItem){//删除
                    loadWaitDialog();
                    HttpMethod.secede(getActivity(), MyCircleFragment.this,circleBean.getHx_id(),circleBean.getId());
                }
            }
        });
        rvCreateByMe.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if(baseQuickAdapter.getData().size()-i>1){
                    CircleListBean.CircleBean circleBean = mCircleMeData.get(i);
                    goChat(circleBean);
                }else{
                    startActivity(CreateCircleActivity.class);
                }
            }
        });
        RxBus.getInstance().toObservable(String.class).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals(ConstantUserInfo.REFRESH_CIRCLE)){
                    onRefresh();
                }
            }
        });
    }

    public void goChat(CircleListBean.CircleBean circleBean){
        MyChatActivity.startGroupChat(getActivity(),circleBean.getHx_id(),circleBean.getId(),circleBean.getName());
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK && requestCode == REQUEST_CHAT_CODE){
//            mCircleData.remove(mCurrentPosition);
            myCircleAdapter.notifyDataSetChanged();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeUser(EventChangeUserBean event){
        onRefresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getCircleData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getCircleData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, myCircleAdapter, null, lvActions, totalSize);
    }

    /**
     * 获取圈子数据
     */
    private void getCircleData(){
        HttpMethod.circleIndex(getActivity(), this, "2", String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if(method == HttpMethod.HTTP_CIRCLE_INDEX1){
            CircleListBean circleListBean = GsonUtil.GsonToListBean(data, CircleListBean.class);
            if(circleListBean != null){
//                totalSize = Integer.parseInt(circleListBean.getNum());
                if (mPage == 1) {
                    mCircleData.clear();
                    mCircleMeData.clear();
                    LoadDataHelper.refreshComplete(myCircleAdapter, mCircleData, refreshLayout, lvActions);
                } else {
                    myCircleAdapter.setEnableLoadMore(true);
                    myCircleAdapter.loadMoreComplete();
                }
                mCircleData.addAll(circleListBean.getAdd_circle());
                myCircleAdapter.notifyDataSetChanged();
                mCircleMeData.addAll(circleListBean.getMy_circle());
                mCircleMeData.add(new CircleListBean.CircleBean());
                mCircleByMeAdapter.notifyDataSetChanged();
            }
        }else if(method == HttpMethod.HTTP_CIRCLE_SECEDE){//退出圈子
            myCircleAdapter.remove(mCurrentPosition);
            myCircleAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void clickViewCallback(int position, int type, View view) {

    }
}
